/**
 * (created at 2011-1-21)
 */
package qiushuo.mysqlparser.ast.expression.primary.literal;

import java.util.HashMap;
import java.util.Map;

import qiushuo.mysqlparser.ast.expression.Expression;
import qiushuo.mysqlparser.ast.expression.primary.PrimaryExpression;
import qiushuo.mysqlparser.generator.SQLType;

/**
 * @author <a href="mailto:QiuShuo1985@gmail.com">QIU Shuo</a>
 */
public class IntervalPrimary extends PrimaryExpression {
    public static enum Unit {
        MICROSECOND,
        SECOND,
        MINUTE,
        HOUR,
        DAY,
        WEEK,
        MONTH,
        QUARTER,
        YEAR,
        SECOND_MICROSECOND,
        MINUTE_MICROSECOND,
        MINUTE_SECOND,
        HOUR_MICROSECOND,
        HOUR_SECOND,
        HOUR_MINUTE,
        DAY_MICROSECOND,
        DAY_SECOND,
        DAY_MINUTE,
        DAY_HOUR,
        YEAR_MONTH
    }

    private static final Map<String, Unit> unitMap = initUnitMap();

    private static Map<String, Unit> initUnitMap() {
        Unit[] units = Unit.class.getEnumConstants();
        Map<String, Unit> map = new HashMap<String, IntervalPrimary.Unit>(units.length);
        for (Unit unit : units) {
            map.put(unit.name(), unit);
        }
        return map;
    }

    /**
     * @param unitString must be upper case, null is forbidden
     */
    public static Unit getIntervalUnit(String unitString) {
        return unitMap.get(unitString);
    }

    private final Unit unit;
    private final Expression quantity;

    public IntervalPrimary(Expression quantity, Unit unit) {
        this.quantity = quantity;
        this.unit = unit;
    }

    @Override
    public String generateSql(SQLType type) {
        switch (type) {
        case MySQL:
            StringBuilder sb = new StringBuilder();
            sb.append("INTERVAL ").append(quantity.generateSql(type)).append(' ').append(unit.name());
            return sb.toString();
        default:
            throw new UnsupportedOperationException("only mysql sql can be generated");
        }
    }

}
